package com.prs.crm.action.crm;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.ToolKits;
import com.prs.crm.domain.crm.Customer;
import com.prs.crm.domain.crm.CustomerAppoint;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.exception.InValidDeleteException;
import com.prs.crm.report.ReportUtils;
import com.prs.crm.service.crm.CustomerAppointService;
import com.prs.crm.service.crm.CustomerService;
import com.prs.crm.service.hr.PersonService;

public class CustomerAppointAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private CustomerAppoint customerAppoint;
	private CustomerAppointService customerAppointService;

	private Person person;
	private PersonService personService;

	private Customer customer;
	private CustomerService customerService;

	private PaginationSupport pagination;
	private Integer[] ids;
	private String levelIds;

	private String appoints;
	private String appointNames;
	private String tradeIds;

	@Action("listPersonAppoint")
	public String execute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Person.class);
		Collection<Integer> ids = this.getCustomerAppointService()
				.findPersonIds();
		pagination = this.getPaginationHelper().prepare(pagination);
		if (ids.size() != 0) {
			criteria.add(Restrictions.in("id", ids));
		}
		this.setPagination(this.getPersonService().listByPage(criteria,
				pagination));

		/*
		 * List<CustomerAppoint> lis = (List<CustomerAppoint>)
		 * this.getPagination().getItems();
		 * 
		 * colls = this.getCustomerAppointService().listPersonAppoint();
		 * 
		 * for(Object[] oss : colls){ for(Object value : oss){ if(value
		 * instanceof Person){ System.out.println(((Person)
		 * value).getResume().getName()); }else if(value instanceof Number){
		 * System.out.println(value); } } }
		 */
		return SUCCESS;
	}

	@Action("editPersonAppoint")
	public String editPersonAppoint() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				CustomerAppoint.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.eq("person", person));
		this.setPagination(this.getCustomerAppointService().listByPage(
				criteria, pagination));
		return SUCCESS;
	}

	@Action(value = "removeCustomerAppoint", results = {
			@Result(name = "success", type = "redirect", location = "editPersonAppoint?person=${person.id}"),
			@Result(name = "error", type = "chain", location = "editPersonAppoint") })
	public String removeCustomerAppoint() {
		try {
			if (ids == null) {
				this.addActionError("请选择要删除的客户信息");
				return ERROR;
			}
			this.getCustomerAppointService().batchRemove(ids);
			return SUCCESS;
		} catch (InValidDeleteException e) {
			// TODO: handle exception
			return ERROR;
		}
	}

	@Action("listCustomerAppoint")
	public String listCustomerAppoint() {
		return SUCCESS;
	}

	@Action("listCustomerAppointByLevel")
	public String listCustomerAppointByLevel() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Customer.class);
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		if (levelIds != null) {
			if (!"all".equals(levelIds)) {
				levelIds = levelIds.split(",")[0];
				if (ToolKits.isInteger(levelIds)) {
					criteria.createAlias("level", "l");
					criteria.add(Restrictions.eq("l.id", Integer
							.parseInt(levelIds)));
				}
			}
		}
		this.setPagination(this.getCustomerService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("editCustomerAppoint")
	public String editCustomerAppoint() {
		appoints = null;
		appointNames = null;
		Set<CustomerAppoint> appointPersons = customer.getAppoints();
		Iterator<CustomerAppoint> iter = appointPersons.iterator();
		while (iter.hasNext()) {
			Person person = iter.next().getPerson();
			appoints = (appoints == null) ? person.getId().toString()
					: appoints + "," + person.getId().toString();
			appointNames = (appointNames == null) ? person.getResume()
					.getName() : appointNames + ","
					+ person.getResume().getName();
		}
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "saveCustomerAppoint", results = {
			@Result(name = "success", type = "redirect", location = "listCustomerAppoint"),
			@Result(name = "error", type = "chain", location = "editCustomerAppoint") })
	public String save() {
		if (appoints == null || "".equals(appoints.trim())) {
			addActionError("客户代表不能为空");
			return ERROR;
		}
		this.setPrompt("提交客户指派成功");
		this.getCustomerAppointService()
				.saveCustomerAppoint(customer, appoints);
		return SUCCESS;
	}

	@Action("listCustomerDelegate")
	public String listCustomerDelegate() {
		return SUCCESS;
	}

	@Action("listCustomerDelegateByTrade")
	public String listCustomerDelegateByTrade() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				CustomerAppoint.class);
		criteria.add(Restrictions.eq("person", AppContext.getAccountContext()
				.currentUser()));
		if (tradeIds != null) {
			if (!"all".equals(tradeIds)) {
				tradeIds = ReportUtils.URLDecode(tradeIds).trim();
				tradeIds = tradeIds.split(",")[0];
				if (ToolKits.isInteger(tradeIds)) {
					criteria.createAlias("customer", "cu");
					criteria.createAlias("cu.trade", "tr");
					criteria.add(Restrictions.eq("tr.id", Integer
							.parseInt(tradeIds)));
				}
			}
		}
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getCustomerAppointService().listByPage(
				criteria, pagination));
		return SUCCESS;
	}

	public CustomerAppoint getCustomerAppoint() {
		return customerAppoint;
	}

	public void setCustomerAppoint(CustomerAppoint customerAppoint) {
		this.customerAppoint = customerAppoint;
	}

	public CustomerAppointService getCustomerAppointService() {
		return customerAppointService;
	}

	public void setCustomerAppointService(
			CustomerAppointService customerAppointService) {
		this.customerAppointService = customerAppointService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public Integer[] getIds() {
		return ids;
	}

	public void setIds(Integer[] ids) {
		this.ids = ids;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public PersonService getPersonService() {
		return personService;
	}

	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public void setAppoints(String appoints) {
		this.appoints = appoints;
	}

	public String getAppoints() {
		return appoints;
	}

	public void setAppointNames(String appointNames) {
		this.appointNames = appointNames;
	}

	public String getAppointNames() {
		return appointNames;
	}

	public String getLevelIds() {
		return levelIds;
	}

	public void setLevelIds(String levelIds) {
		this.levelIds = levelIds;
	}

	public String getTradeIds() {
		return tradeIds;
	}

	public void setTradeIds(String tradeIds) {
		this.tradeIds = tradeIds;
	}

}
